<template>
  <div class="image-uploader">
    <el-upload :data="data" :action="api.admin_uploader" :headers="headers" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload" drag accept="image/*" name="file">
      <div v-if="!(localImg || remoteImage)">
        <i class="el-icon-plus image-uploader-icon" :style="icon_style"/>
        <span v-if="size" class="image-uploader-tips">{{ $t('tips.size') + ': ' + size }}</span>
      </div>
    </el-upload>
    <div v-show="localImg || remoteImage" class="image-preview image-app-preview">
      <div class="image-preview-wrapper">
        <img :src="localImg || remoteImage" class="image-uploader-img">
        <div class="image-preview-action">
          <i class="el-icon-delete" @click="rmImage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getXsrftoken } from '@/utils/auth'

export default {
  props: { action: String, remoteImage: String, size: String, icon_style: String},
  data() {
    return {
      imgUrl: '',
      localImg: '',
      headers: {
        'X-Xsrftoken': getXsrftoken()
      },
      data: {
        path: this.action,
        action: this.action
      },
      uploadImg: undefined,
      actionApi: this.api.admin_uploader
    }
  },
  watch: {
    remoteImage() {
      if (this.remoteImage !== this.uploadImg) {
        this.localImg = undefined
      }
    }
  },
  methods: {
    rmImage() {
      this.$emit('uploadImgData', '')
    },
    handleSuccess(response, file) {
      if (response.code === 0) {
        this.localImg = URL.createObjectURL(file.raw)
        this.uploadImg = response.data.path_file
        this.$emit('uploadImgData', response.data.path_file)
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
    }
  }
}
</script>

<style>
.el-upload--text {
  width: auto !important;
}
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  float:left;
}
.image-uploader .el-upload:hover {
  border-color: #409eff;
}
.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  height: 178px;
  min-width: 178px !important;
  line-height: 178px;
  text-align: center;
}
.image-uploader-icon::before {
  line-height: 178px;
}
.image-uploader-img {
  height: 178px;
  display: block;
}
.image-uploader-tips {
  position: absolute;
  left: 5px;
  bottom: 5px;
}
.image-uploader .el-upload-dragger {
  width: auto;
  height: auto;
}
</style>
